var logger = require('../libs/log').logger;
var _ = require('underscore');
var { wxpay, MathCode } = require('../libs/common');
var { appid, wx_mch_id, wx_mch_key, notify_url, trade_type, notify_url_back } = require('../../server_config.json').wechat;
const { Add, Update, QueryOne, Exec_Count, Exec, Query, ExecGetOne, ExecSqlparmater } = require('../db/dbhelper');

const WxPay = require('wechatpay-node-v3');
const fs = require('fs');

// 创建支付实例
const pay = new WxPay({
    appid: appid,
    mchid: wx_mch_id,
    publicKey: fs.readFileSync('./apiclient_cert.pem'), // 公钥
    privateKey: fs.readFileSync('./apiclient_key.pem'), // 秘钥
});
// 拿到支付所需参数
async function unifiedorder(openid, money, orderCode, paybody, spbill_create_ip) {
    try {
        // 接收前端传过来的openid
        const params = {
            description: paybody, // 订单描述
            out_trade_no: orderCode, // 订单号，一般每次发起支付都要不一样，可使用随机数生成
            notify_url: notify_url,
            amount: {
                total: wxpay.getmoney(money), // 支付金额，单位为分
            },
            payer: {
                openid: openid, // 微信小程序用户的openid，一般需要前端发送过来
            },
            scene_info: {
                payer_client_ip: spbill_create_ip, // 支付者ip，这个不用理会也没有问题
            },
        };
        const result = await pay.transactions_jsapi(params);
        logger.info('-------payInfo-----result,', JSON.stringify(result));
        // 更新订单信息
        await ExecSqlparmater('update hzz_orders set start_time=?, paytype=? where ordercode =? ',[new Date(), trade_type, orderCode]);
        // 将结果响应给微信小程序前端
        return _.omit(result,'appId');
    } catch (error) {
        logger.info('-------payInfo-----error,', error)
    }
}

async function decodeData(doc){
    // 申请的APIv3
    let key = wx_mch_key;
    let { ciphertext, associated_data, nonce } = doc;
    // 解密回调信息
    const result = pay.decipher_gcm(ciphertext, associated_data, nonce, key);
    return result;
}

async function payto(doc, ip) {
    try {
        logger.info('---------payto----,doc:',doc)
        let { pcode, activeid } = doc;
        if (!pcode) {
            return {
                code: 1,
                msg: '缺失参数pcode'
            }
        }
        if (!activeid) {
            return {
                code: 1,
                msg: '缺失参数activeid'
            }
        }
        let orderData = await QueryOne('hzz_orders', { pcode: pcode, activeid: activeid });
        let peoData = await QueryOne('hzz_peoples', { code: pcode }, 'openid');
        if (!orderData) {
            return {
                code: 1,
                msg: '该用户尚未报名，请先报名经平台审核！'
            }
        }
        if (orderData.auditstatus != 1) {
            return {
                code: 1,
                msg: '平台尚未审核通过，暂不能支付！'
            }
        }
        if (orderData.paystatus == 1) {
            return {
                code: 1,
                msg: '您已支付过了，无需重复支付！'
            }
        }
        if (!peoData) {
            return {
                code: 1,
                msg: '用户信息丢失，请刷新小程序！'
            }
        }
        // 创建微信支付订单
        // 已创建订单的，重新生成订单号
        if(orderData.transactions_info){
            orderData.ordercode = MathCode();
            await Exec(`update hzz_orders set ordercode = '${orderData.ordercode}' where id = ${orderData.id}`);
        }
        let data = await unifiedorder(peoData.openid, orderData.price, orderData.ordercode, '红豆家缘活动报名', ip);
        logger.info('---------payto----,data:',data)
        return {
            code: 0,
            data: data
        };
    } catch (error) {
        return {
            code: 1,
            msg: '系统异常，请联系客服'
        }
    }
}
// 退款
/**
 * 
 * @param {*} ordercode 订单编号
 * @param {*} refund_money 退款金额
 * @param {*} origin_money 订单原金额
 */
async function refunds(doc){
    let { ordercode, refund_money, origin_money } = doc;
    let params = {
        //"transaction_id": "1217752501201407033233368018",
        "out_trade_no": ordercode,
        "out_refund_no": MathCode(),
        "reason": "活动守时费退款",
        "notify_url": notify_url_back, // 回调地址
        "funds_account": "AVAILABLE",
        "amount": {
          "refund": refund_money, //退款金额
        //   "from": [
        //     {
        //       "account": "AVAILABLE",
        //       "amount": 444
        //     }
        //   ],
          "total": origin_money,
          "currency": "CNY"
        },
        // "goods_detail": [
        //   {
        //     "merchant_goods_id": "1217752501201407033233368018",
        //     "wechatpay_goods_id": "1001",
        //     "goods_name": "iPhone6s 16G",
        //     "unit_price": 528800,
        //     "refund_amount": 528800,
        //     "refund_quantity": 1
        //   }
        // ]
    };
    logger.info('----退款-----refunds:',params);
    let result = await pay.refunds(params);
    // 更新订单信息
    await ExecSqlparmater('update hzz_orders set backtime=?, backstatus=?, refunds_info=? where ordercode =? ',[new Date(), result.status, JSON.stringify(result), ordercode]);
    logger.info('----退款-----result:',result);
}

module.exports = {
    payto,
    unifiedorder,
    decodeData,
    refunds
};